//
//  ViewController.swift
//  6.9.Adding Custom Interactions to Collection Views
//
//  Created by joker on 15/8/9.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UICollectionViewController {

    let allImages = [
        UIImage(named: "1"),
        UIImage(named: "2"),
        UIImage(named: "3")
    ]
    
    
    let animationDuration: NSTimeInterval = 1
    
    func randomImage() ->UIImage {
        return allImages[Int( arc4random_uniform(UInt32(allImages.count))) ]!
    }
    
    override init(collectionViewLayout layout: UICollectionViewLayout) {
        super.init(collectionViewLayout: layout)
        
        let nib = UINib(nibName: "myCollectionViewCell", bundle: nil)
        
        let headerNib = UINib(nibName: "Header", bundle: nil)
        let footerNib = UINib(nibName: "Footer", bundle: nil)
        
        
        
        collectionView?.registerNib(nib, forCellWithReuseIdentifier: "cell")
        
        collectionView?.registerNib(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
        
        collectionView?.registerNib(footerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footer")
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    convenience required init(coder aDecoder: NSCoder) {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.minimumLineSpacing = 20
        flowLayout.minimumInteritemSpacing = 10
        
        flowLayout.itemSize = CGSize(width: 80, height: 120)
        
        flowLayout.scrollDirection = .Vertical
        
        flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20)
        
        
        flowLayout.headerReferenceSize = CGSize(width: 300, height: 50)
        flowLayout.footerReferenceSize = CGSize(width: 300, height: 50)
        self.init(collectionViewLayout: flowLayout)
    }
    
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return Int(3 + arc4random_uniform(4))
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return Int(10 + arc4random_uniform(6))
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! myCollectionViewCell
        
        cell.imageViewBackgroundImage.image = randomImage()
        cell.imageViewBackgroundImage.contentMode = .ScaleAspectFit
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let selectedCell = collectionView.cellForItemAtIndexPath(indexPath)
        
        UIView.animateWithDuration(animationDuration, animations: {
            selectedCell?.alpha = 0
            }
            , completion: {[weak self] (finished: Bool) in
                UIView.animateWithDuration(self!.animationDuration, animations: {
                selectedCell?.alpha = 1
                })
        })
    }
    
    
    override func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
        let selectedCell = collectionView.cellForItemAtIndexPath(indexPath)
        
        UIView.animateWithDuration(animationDuration, animations: {
            selectedCell?.transform = CGAffineTransformMakeScale(4, 4)
        })
    }
    override func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
        let selectedCell = collectionView.cellForItemAtIndexPath(indexPath)
        
        UIView.animateWithDuration(animationDuration, animations: {
            selectedCell?.transform = CGAffineTransformIdentity
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let pinch = UIPinchGestureRecognizer(target: self, action: "handlePin:")
        
        for recoginzer in collectionView?.gestureRecognizers as! [UIGestureRecognizer] {
            if recoginzer is UIPinchGestureRecognizer {
                recoginzer.requireGestureRecognizerToFail(pinch)
            }
        }
        collectionView?.addGestureRecognizer(pinch)
    }
    func handlePin(pinch: UIPinchGestureRecognizer) {
        
        let defaultLayoutItemSize = CGSize(width: 80, height: 120)
        
        let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: defaultLayoutItemSize.width * pinch.scale, height: defaultLayoutItemSize.height * pinch.scale)
        
        layout.invalidateLayout()
        
    }
    
    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

        var identifier = "header"
        

        if kind == UICollectionElementKindSectionFooter {
            identifier = "footer"
        }
        
        let view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: identifier, forIndexPath: indexPath) as! UICollectionReusableView
        
        if kind == UICollectionElementKindSectionHeader {
            if let header = view as? myHeader {
                header.label.text = "Section \(indexPath.section) Header"
            }
        }
        else if kind == UICollectionElementKindSectionFooter {
            if let footer = view as? Footer {
                let title = "Section \(indexPath.section) Footer"
                footer.button.setTitle(title, forState: .Normal)
            }
        }
        return view
    }
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

